/**   
 *    
 * 项目名称：a_yongan   
 * 类名称：ProcessProcessServiceImpl   
 * 类描述：   
 * 创建人：liubo   
 * 创建时间：2018年6月18日 下午2:10:43    
 * 修改时间：2018年6月18日 下午2:10:43   
 * 修改备注：   
 * @version    
 *    
 */
package com.yongan.production.service.impl;

import java.util.List;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import com.yongan.production.dao.GoodassembleDao;
import com.yongan.production.entity.Details;
import com.yongan.production.entity.Goodassemble;
import com.yongan.production.service.DetailsService;
import com.yongan.production.service.GoodassembleService;
import com.yongan.user.enums.UserStatEnum;
import com.yongan.user.exception.UserException;
import com.yongan.util.Execution;
import com.yongan.warehouse.dao.GoodsinformationDao;
import com.yongan.warehouse.entity.Goodsinformation;
import com.yongan.warehouse.service.GoodsinformationService;

/**
 * @author liubo
 * 
 */
@Service
public class GoodassembleServiceImpl implements GoodassembleService {

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private GoodassembleDao goodassembleDao;
	@Autowired
	private DetailsService detailsService;
	@Autowired
	private GoodsinformationService goodsinformationService;
	@Autowired
	private GoodsinformationDao goodsinformationDao;
	private final String slat = "dsjdajsdkHJJHAJAKdsd921e0p12*DAe#@$@!qew";

	@Override
	public List<Goodassemble> getGoodassemble(int offset, int limit) {
		List<Goodassemble> list = goodassembleDao.queryAll(offset, limit);
		return list;
	}

	@Override
	public Goodassemble getGoodassembleById(String goodassembleId) {
		Goodassemble goodassemble = goodassembleDao
				.queryById(goodassembleId);
		goodassemble.setDetails(detailsService.getDetailsList(goodassembleId));
		goodassemble.setGoodassembleGoods(goodsinformationDao.queryById(goodassemble.getGoodassembleGoodsId()));
		return goodassemble;
	}

	@Transactional
	@Override
	public Execution executeGoodassemble(Goodassemble goodassemble,
			String goodassembleId, String md5) throws UserException {
		if (md5 == null || !md5.equals(getMD5(goodassembleId))) {
			// throw new UserException("user data rewrite");
		}
		try {
			if (goodassemble == null) {
				Goodassemble pp = goodassembleDao.queryById(goodassembleId);
				int deleteDetails;
				int deleteCount;
				if(pp.getIsChu().equals("true")){
					if(pp.getIsRu().equals("true")){
						return new Execution(goodassembleId, UserStatEnum.FAILED);//商品已组装完成，无法删除
					}
					List<Details> detailsall = detailsService.getDetailsList(goodassembleId);
					for(Details d:detailsall){
						int reduceCount = reduceNumber(d, "add");
						if (reduceCount <= 0) {
							throw new UserException("delete failed");
						}
					}
					deleteDetails = detailsService.deleteAllByTopId(goodassembleId);
					deleteCount = goodassembleDao.deleteGoodassemble(goodassembleId);
				}else{
					//List<Details> detailsall = detailsService.getDetailsList(goodassembleId);
					deleteDetails = detailsService.deleteAllByTopId(goodassembleId);
					deleteCount = goodassembleDao.deleteGoodassemble(goodassembleId);
				}
				if (deleteCount <= 0 & deleteDetails <= 0) {
					throw new UserException("delete failed");
				} else {
					return new Execution(goodassembleId, UserStatEnum.SUCCESS);
				}
			} else if ((goodassembleId.equals(""))) {
				String topId = UUID.randomUUID().toString();
				goodassemble.setGoodassembleId(topId);;
				int addCount = goodassembleDao
						.insertGoodassemble(goodassemble);
				List<Details> details = goodassemble.getDetails();
				Boolean isDetails = false;
				for (Details detail : details) {
					detail.setDetailsId(UUID.randomUUID().toString());
					detail.setTopId(topId);
					int detailAdd = detailsService
							.addDetails(detail);
					if (detailAdd <= 0) {
						isDetails = true;
					}
				}
				if (addCount <= 0 & isDetails) {
					throw new UserException("add failed");
				} else {
					return new Execution(goodassemble.getGoodassembleId(),
							UserStatEnum.SUCCESS);
				}
			} else if (!(goodassembleId.equals(""))) {
				int updateCount = goodassembleDao
						.updateGoodassemble(goodassemble);
				List<Details> details = goodassemble.getDetails();
				System.out.println("==="+details);
				Boolean isDetails = false;
				for (Details detail : details) {
					int detailsCount = detailsService
							.updateDetails(detail);
					if (detailsCount <= 0) {
						isDetails = true;
					}
				}
				if (updateCount <= 0 & isDetails) {
					throw new UserException("update failed");
				} else {
					return new Execution(goodassembleId, UserStatEnum.SUCCESS);
				}
			} else {
				throw new UserException("parameter error");
			}

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new UserException("inner error:" + e.getMessage());
		}
	}

	public int getCount() {
		return goodassembleDao.queryCount();
	}

	private String getMD5(String Id) {
		String base = Id + "/" + slat;
		String md5 = DigestUtils.md5DigestAsHex(base.getBytes());
		return md5;
	}

	@Transactional
	@Override
	public Execution executeChuku(String goodassembleId,
			List<Details> detailsall, String md5) throws UserException {
		// ProcessProcess pp = processProcessDao.queryById(processProcessId);
		//Details detail = detailsall.get(detailsall.size() - 1);
		try {
			Boolean is = false;
			for(Details d:detailsall){
				int jie = reduceNumber(d, "reduce");
				if (jie <= 0) {
					is = true;
				}
			}
			int zhu = goodassembleDao.updateChuku("true", goodassembleId);
			if (!is & zhu <= 0) {
				throw new UserException("chuku failed");
			} else {
				return new Execution("", UserStatEnum.SUCCESS);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new UserException("inner error:" + e.getMessage());
		}
	}

	@Transactional
	@Override
	public Execution executeRuku(String goodassembleId, String md5) throws UserException {
		Goodassemble pp = goodassembleDao.queryById(goodassembleId);
		//Details detail = detailsall.get(detailsall.size() - 1);
		try {
			int jie = reduceMainNumber(pp, "add");
			int zhu = goodassembleDao.updateRuku("true", goodassembleId);
			if (jie <= 0 & zhu <= 0) {
				throw new UserException("ruku failed");
			} else {
				return new Execution("", UserStatEnum.SUCCESS);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new UserException("inner error:" + e.getMessage());
		}
	}
	public int reduceNumber(Details igd, String type) {
		Goodsinformation gi = goodsinformationDao.queryById(igd
				.getDetailsPid());
		return goodsinformationDao.reduceNumber(gi.getGoodsinformationNumber(),
				type, Integer.parseInt(igd.getDetailsSl()),
				Integer.parseInt(igd.getDetailsSl()));
	}
	public int reduceMainNumber(Goodassemble igd, String type) {
		return goodsinformationDao.reduceNumber(igd.getGoodassembleHpbm(),
				type, Integer.parseInt(igd.getGoodassembleZzsl()),
				Integer.parseInt(igd.getGoodassembleZzsl()));
	}
}
